import { STORAGE_KEYS } from '@/constants/storage';
import { storageService } from '@/services/storage';
import type { OperationResult } from '@/types/common/base';
import type { 
  ICourse, 
  ICourseCreateRequest, 
  ICourseUpdateRequest, 
  ICourseQueryParams,
  ICourseStatistics,
  ICourseSummary,
  ICourseDetail
} from '@/types/course/course';
import type { ICourseCategory } from '@/types/course/courseCategory';
import { CourseStatusEnum } from '@/types/course/enums';

/**
 * 课程验证结果接口
 */
interface ICourseValidationResult {
  /** 是否验证通过 */
  isValid: boolean;
  /** 错误信息列表 */
  errors: string[];
}

/**
 * 课程服务类
 * @description 负责课程数据的增删改查和业务逻辑处理
 */
export class CourseService {
  /**
   * 获取所有课程
   * @param queryParams 查询参数
   * @returns 课程列表
   */
  async getAllCourses(queryParams?: ICourseQueryParams): Promise<OperationResult<ICourse[]>> {
    try {
      const result = await storageService.getItem<ICourse[]>(STORAGE_KEYS.COURSES);
      
      if (!result.success) {
        // 如果没有数据，返回空数组
        if (result.errorCode === 'INVALID_DATA_FORMAT') {
          return {
            success: true,
            data: []
          };
        }
        return result;
      }

      let courses = result.data || [];

      // 过滤已删除的课程
      courses = courses.filter(course => course.status !== CourseStatusEnum.DELETED);

      // 应用查询参数
      if (queryParams) {
        courses = this.filterCourses(courses, queryParams);
      }

      return {
        success: true,
        data: courses
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取课程列表失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 根据ID获取课程
   * @param id 课程ID
   * @returns 课程信息
   */
  async getCourseById(id: string): Promise<OperationResult<ICourse>> {
    try {
      const coursesResult = await this.getAllCourses();
      if (!coursesResult.success) {
        return coursesResult;
      }

      const course = coursesResult.data.find(c => c.id === id);
      if (!course) {
        return {
          success: false,
          error: '课程不存在'
        };
      }

      return {
        success: true,
        data: course
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取课程信息失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 根据课程代码获取课程
   * @param courseCode 课程代码
   * @returns 课程信息
   */
  async getCourseByCourseCode(courseCode: string): Promise<OperationResult<ICourse>> {
    try {
      const coursesResult = await this.getAllCourses();
      if (!coursesResult.success) {
        return coursesResult;
      }

      const course = coursesResult.data.find(c => c.courseCode === courseCode);
      if (!course) {
        return {
          success: false,
          error: '课程不存在'
        };
      }

      return {
        success: true,
        data: course
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取课程信息失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 获取课程详情（包含关联数据）
   * @param id 课程ID
   * @returns 课程详情
   */
  async getCourseDetail(id: string): Promise<OperationResult<ICourseDetail>> {
    try {
      const courseResult = await this.getCourseById(id);
      if (!courseResult.success) {
        return courseResult;
      }

      const course = courseResult.data;

      // 获取关联的分类信息
      const categoriesResult = await storageService.getItem<ICourseCategory[]>(STORAGE_KEYS.COURSE_CATEGORIES);
      const allCategories = categoriesResult.success ? categoriesResult.data || [] : [];
      
      const categories = allCategories
        .filter(cat => course.categoryIds.includes(cat.id))
        .map(cat => ({
          id: cat.id,
          name: cat.name,
          color: cat.color
        }));

      // 获取先修课程信息
      let prerequisiteCourses: ICourseSummary[] = [];
      if (course.prerequisites && course.prerequisites.length > 0) {
        const allCoursesResult = await this.getAllCourses();
        if (allCoursesResult.success) {
          prerequisiteCourses = allCoursesResult.data
            .filter(c => course.prerequisites!.includes(c.id))
            .map(c => ({
              id: c.id,
              name: c.name,
              courseCode: c.courseCode,
              teacher: c.teacher,
              color: c.color,
              status: c.status,
              duration: c.duration,
              fee: c.fee
            }));
        }
      }

      // 获取学生数量和课程实例数量
      const studentCount = await this.getCourseStudentCount(id);
      const scheduleCount = await this.getCourseScheduleCount(id);

      // 获取最近课程时间
      const lastScheduleTime = await this.getLastScheduleTime(id);

      const courseDetail: ICourseDetail = {
        ...course,
        categories,
        prerequisiteCourses,
        studentCount,
        scheduleCount,
        lastScheduleTime
      };

      return {
        success: true,
        data: courseDetail
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取课程详情失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 创建课程
   * @param courseData 课程数据
   * @returns 创建的课程信息
   */
  async createCourse(courseData: ICourseCreateRequest): Promise<OperationResult<ICourse>> {
    try {
      // 数据验证
      const validationResult = this.validateCourseData(courseData);
      if (!validationResult.isValid) {
        return {
          success: false,
          error: validationResult.errors.join('; ')
        };
      }

      // 检查课程代码是否已存在
      const existingCourseResult = await this.getCourseByCourseCode(courseData.courseCode);
      if (existingCourseResult.success) {
        return {
          success: false,
          error: `课程代码 ${courseData.courseCode} 已存在`
        };
      }

      // 验证分类ID是否存在
      const categoryValidationResult = await this.validateCategoryIds(courseData.categoryIds);
      if (!categoryValidationResult.success) {
        return categoryValidationResult;
      }

      // 验证先修课程ID是否存在
      if (courseData.prerequisites && courseData.prerequisites.length > 0) {
        const prerequisiteValidationResult = await this.validatePrerequisiteIds(courseData.prerequisites);
        if (!prerequisiteValidationResult.success) {
          return prerequisiteValidationResult;
        }
      }

      // 获取现有课程列表
      const coursesResult = await this.getAllCourses();
      if (!coursesResult.success) {
        return coursesResult;
      }

      const courses = coursesResult.data;

      // 创建新课程对象
      const now = Date.now();
      const newCourse: ICourse = {
        id: this.generateCourseId(),
        ...courseData,
        status: courseData.status || CourseStatusEnum.ACTIVE,
        color: courseData.color || this.generateRandomColor(),
        createdAt: now,
        updatedAt: now
      };

      // 添加到课程列表
      courses.push(newCourse);

      // 保存到存储
      const saveResult = await storageService.setItem(STORAGE_KEYS.COURSES, courses, {
        createBackup: true
      });

      if (!saveResult.success) {
        return saveResult;
      }

      return {
        success: true,
        data: newCourse
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '创建课程失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 更新课程信息
   * @param id 课程ID
   * @param updateData 更新数据
   * @returns 更新后的课程信息
   */
  async updateCourse(id: string, updateData: Omit<ICourseUpdateRequest, 'id'>): Promise<OperationResult<ICourse>> {
    try {
      // 获取现有课程列表
      const coursesResult = await this.getAllCourses();
      if (!coursesResult.success) {
        return coursesResult;
      }

      const courses = coursesResult.data;
      const courseIndex = courses.findIndex(c => c.id === id);

      if (courseIndex === -1) {
        return {
          success: false,
          error: '课程不存在'
        };
      }

      const existingCourse = courses[courseIndex];

      // 如果更新课程代码，检查新代码是否已存在
      if (updateData.courseCode && updateData.courseCode !== existingCourse.courseCode) {
        const existingCourseResult = await this.getCourseByCourseCode(updateData.courseCode);
        if (existingCourseResult.success) {
          return {
            success: false,
            error: `课程代码 ${updateData.courseCode} 已存在`
          };
        }
      }

      // 验证分类ID是否存在
      if (updateData.categoryIds) {
        const categoryValidationResult = await this.validateCategoryIds(updateData.categoryIds);
        if (!categoryValidationResult.success) {
          return categoryValidationResult;
        }
      }

      // 验证先修课程ID是否存在
      if (updateData.prerequisites && updateData.prerequisites.length > 0) {
        const prerequisiteValidationResult = await this.validatePrerequisiteIds(updateData.prerequisites);
        if (!prerequisiteValidationResult.success) {
          return prerequisiteValidationResult;
        }
      }

      // 合并更新数据
      const updatedCourse: ICourse = {
        ...existingCourse,
        ...updateData,
        id, // 确保ID不被修改
        updatedAt: Date.now()
      };

      // 验证更新后的数据
      const validationResult = this.validateCourseData(updatedCourse);
      if (!validationResult.isValid) {
        return {
          success: false,
          error: validationResult.errors.join('; ')
        };
      }

      // 更新课程列表
      courses[courseIndex] = updatedCourse;

      // 保存到存储
      const saveResult = await storageService.setItem(STORAGE_KEYS.COURSES, courses, {
        createBackup: true
      });

      if (!saveResult.success) {
        return saveResult;
      }

      return {
        success: true,
        data: updatedCourse
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '更新课程信息失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 删除课程（软删除）
   * @param id 课程ID
   * @returns 操作结果
   */
  async deleteCourse(id: string): Promise<OperationResult<void>> {
    try {
      // 检查课程是否有关联的课表
      const hasScheduleResult = await this.checkCourseHasSchedule(id);
      if (!hasScheduleResult.success) {
        return hasScheduleResult;
      }

      if (hasScheduleResult.data) {
        return {
          success: false,
          error: '该课程有关联的课程安排，请先删除相关课表后再删除课程'
        };
      }

      // 软删除：将状态设置为已删除
      const updateResult = await this.updateCourse(id, {
        status: CourseStatusEnum.DELETED
      });

      if (!updateResult.success) {
        return updateResult;
      }

      return {
        success: true,
        data: undefined
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '删除课程失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 批量删除课程
   * @param ids 课程ID列表
   * @returns 操作结果
   */
  async batchDeleteCourses(ids: string[]): Promise<OperationResult<{ successCount: number; failedCount: number; errors: string[] }>> {
    try {
      let successCount = 0;
      let failedCount = 0;
      const errors: string[] = [];

      for (const id of ids) {
        const result = await this.deleteCourse(id);
        if (result.success) {
          successCount++;
        } else {
          failedCount++;
          errors.push(`课程 ${id}: ${result.error}`);
        }
      }

      return {
        success: true,
        data: {
          successCount,
          failedCount,
          errors
        }
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '批量删除课程失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 获取课程统计信息
   * @returns 统计信息
   */
  async getCourseStatistics(): Promise<OperationResult<ICourseStatistics>> {
    try {
      const coursesResult = await this.getAllCourses();
      if (!coursesResult.success) {
        return coursesResult;
      }

      const courses = coursesResult.data;

      // 基础统计
      const totalCount = courses.length;
      const activeCount = courses.filter(c => c.status === CourseStatusEnum.ACTIVE).length;
      const suspendedCount = courses.filter(c => c.status === CourseStatusEnum.SUSPENDED).length;
      const deletedCount = courses.filter(c => c.status === CourseStatusEnum.DELETED).length;

      // 获取分类信息
      const categoriesResult = await storageService.getItem<ICourseCategory[]>(STORAGE_KEYS.COURSE_CATEGORIES);
      const allCategories = categoriesResult.success ? categoriesResult.data || [] : [];

      // 分类分布统计
      const categoryMap = new Map<string, { name: string; count: number }>();
      courses.forEach(course => {
        course.categoryIds.forEach(categoryId => {
          const category = allCategories.find(cat => cat.id === categoryId);
          if (category) {
            const existing = categoryMap.get(categoryId);
            if (existing) {
              existing.count++;
            } else {
              categoryMap.set(categoryId, { name: category.name, count: 1 });
            }
          }
        });
      });

      const categoryDistribution = Array.from(categoryMap.entries()).map(([categoryId, info]) => ({
        categoryId,
        categoryName: info.name,
        count: info.count
      }));

      // 教师分布统计
      const teacherMap = new Map<string, number>();
      courses.forEach(course => {
        teacherMap.set(course.teacher, (teacherMap.get(course.teacher) || 0) + 1);
      });
      const teacherDistribution = Array.from(teacherMap.entries()).map(([teacher, count]) => ({
        teacher,
        count
      }));

      // 难度等级分布统计
      const levelMap = new Map<'beginner' | 'intermediate' | 'advanced', number>();
      courses.forEach(course => {
        if (course.level) {
          levelMap.set(course.level, (levelMap.get(course.level) || 0) + 1);
        }
      });
      const levelDistribution = Array.from(levelMap.entries()).map(([level, count]) => ({
        level,
        count
      }));

      // 平均费用和时长
      const coursesWithFee = courses.filter(c => c.fee && c.fee > 0);
      const averageFee = coursesWithFee.length > 0 
        ? coursesWithFee.reduce((sum, c) => sum + (c.fee || 0), 0) / coursesWithFee.length 
        : 0;

      const coursesWithDuration = courses.filter(c => c.duration && c.duration > 0);
      const averageDuration = coursesWithDuration.length > 0 
        ? coursesWithDuration.reduce((sum, c) => sum + (c.duration || 0), 0) / coursesWithDuration.length 
        : 0;

      const statistics: ICourseStatistics = {
        totalCount,
        activeCount,
        suspendedCount,
        deletedCount,
        categoryDistribution,
        teacherDistribution,
        levelDistribution,
        averageFee,
        averageDuration
      };

      return {
        success: true,
        data: statistics
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取课程统计信息失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 获取课程简要信息列表
   * @param queryParams 查询参数
   * @returns 课程简要信息列表
   */
  async getCourseSummaries(queryParams?: ICourseQueryParams): Promise<OperationResult<ICourseSummary[]>> {
    try {
      const coursesResult = await this.getAllCourses(queryParams);
      if (!coursesResult.success) {
        return coursesResult;
      }

      const summaries: ICourseSummary[] = coursesResult.data.map(course => ({
        id: course.id,
        name: course.name,
        courseCode: course.courseCode,
        teacher: course.teacher,
        color: course.color,
        status: course.status,
        duration: course.duration,
        fee: course.fee
      }));

      return {
        success: true,
        data: summaries
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取课程简要信息失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 搜索课程
   * @param keyword 搜索关键词
   * @param limit 结果数量限制
   * @returns 搜索结果
   */
  async searchCourses(keyword: string, limit: number = 10): Promise<OperationResult<ICourse[]>> {
    try {
      if (!keyword.trim()) {
        return {
          success: true,
          data: []
        };
      }

      const coursesResult = await this.getAllCourses();
      if (!coursesResult.success) {
        return coursesResult;
      }

      const courses = coursesResult.data;
      const lowerKeyword = keyword.toLowerCase();

      const matchedCourses = courses.filter(course => 
        course.name.toLowerCase().includes(lowerKeyword) ||
        course.courseCode.toLowerCase().includes(lowerKeyword) ||
        course.teacher.toLowerCase().includes(lowerKeyword) ||
        (course.description && course.description.toLowerCase().includes(lowerKeyword)) ||
        (course.tags && course.tags.some(tag => tag.toLowerCase().includes(lowerKeyword)))
      );

      // 按相关性排序（课程名称匹配优先）
      matchedCourses.sort((a, b) => {
        const aNameMatch = a.name.toLowerCase().includes(lowerKeyword);
        const bNameMatch = b.name.toLowerCase().includes(lowerKeyword);
        
        if (aNameMatch && !bNameMatch) return -1;
        if (!aNameMatch && bNameMatch) return 1;
        
        return a.name.localeCompare(b.name);
      });

      return {
        success: true,
        data: matchedCourses.slice(0, limit)
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '搜索课程失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 根据分类获取课程
   * @param categoryId 分类ID
   * @returns 课程列表
   */
  async getCoursesByCategory(categoryId: string): Promise<OperationResult<ICourse[]>> {
    try {
      const coursesResult = await this.getAllCourses();
      if (!coursesResult.success) {
        return coursesResult;
      }

      const courses = coursesResult.data.filter(course => 
        course.categoryIds.includes(categoryId)
      );

      return {
        success: true,
        data: courses
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '获取分类课程失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 更新课程分类关联
   * @param courseId 课程ID
   * @param categoryIds 分类ID列表
   * @returns 操作结果
   */
  async updateCourseCategories(courseId: string, categoryIds: string[]): Promise<OperationResult<ICourse>> {
    try {
      // 验证分类ID是否存在
      const categoryValidationResult = await this.validateCategoryIds(categoryIds);
      if (!categoryValidationResult.success) {
        return categoryValidationResult;
      }

      // 更新课程分类
      const updateResult = await this.updateCourse(courseId, {
        categoryIds
      });

      return updateResult;

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '更新课程分类失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 验证课程数据
   * @param courseData 课程数据
   * @returns 验证结果
   */
  private validateCourseData(courseData: Partial<ICourse>): ICourseValidationResult {
    const errors: string[] = [];

    // 必填字段验证
    if (!courseData.name || !courseData.name.trim()) {
      errors.push('课程名称不能为空');
    }

    if (!courseData.courseCode || !courseData.courseCode.trim()) {
      errors.push('课程代码不能为空');
    }

    if (!courseData.teacher || !courseData.teacher.trim()) {
      errors.push('授课教师不能为空');
    }

    if (!courseData.categoryIds || courseData.categoryIds.length === 0) {
      errors.push('课程分类不能为空');
    }

    // 格式验证
    if (courseData.name && courseData.name.length > 100) {
      errors.push('课程名称长度不能超过100个字符');
    }

    if (courseData.courseCode && courseData.courseCode.length > 50) {
      errors.push('课程代码长度不能超过50个字符');
    }

    if (courseData.teacher && courseData.teacher.length > 50) {
      errors.push('授课教师长度不能超过50个字符');
    }

    if (courseData.duration && (courseData.duration < 1 || courseData.duration > 1440)) {
      errors.push('课程时长必须在1-1440分钟之间');
    }

    if (courseData.fee && courseData.fee < 0) {
      errors.push('课程费用不能为负数');
    }

    if (courseData.capacity && (courseData.capacity < 1 || courseData.capacity > 1000)) {
      errors.push('课程容量必须在1-1000人之间');
    }

    return {
      isValid: errors.length === 0,
      errors
    };
  }

  /**
   * 过滤课程列表
   * @param courses 课程列表
   * @param queryParams 查询参数
   * @returns 过滤后的课程列表
   */
  private filterCourses(courses: ICourse[], queryParams: ICourseQueryParams): ICourse[] {
    return courses.filter(course => {
      // 课程名称模糊搜索
      if (queryParams.name && !course.name.toLowerCase().includes(queryParams.name.toLowerCase())) {
        return false;
      }

      // 课程代码精确匹配
      if (queryParams.courseCode && course.courseCode !== queryParams.courseCode) {
        return false;
      }

      // 教师模糊搜索
      if (queryParams.teacher && !course.teacher.toLowerCase().includes(queryParams.teacher.toLowerCase())) {
        return false;
      }

      // 分类匹配
      if (queryParams.categoryId && !course.categoryIds.includes(queryParams.categoryId)) {
        return false;
      }

      if (queryParams.categoryIds && !queryParams.categoryIds.some(id => course.categoryIds.includes(id))) {
        return false;
      }

      // 状态匹配
      if (queryParams.status && course.status !== queryParams.status) {
        return false;
      }

      // 难度等级匹配
      if (queryParams.level && course.level !== queryParams.level) {
        return false;
      }

      // 标签匹配
      if (queryParams.tags && queryParams.tags.length > 0) {
        const hasMatchingTag = queryParams.tags.some(tag => 
          course.tags && course.tags.includes(tag)
        );
        if (!hasMatchingTag) {
          return false;
        }
      }

      // 费用范围
      if (queryParams.minFee && (!course.fee || course.fee < queryParams.minFee)) {
        return false;
      }

      if (queryParams.maxFee && (!course.fee || course.fee > queryParams.maxFee)) {
        return false;
      }

      // 时长范围
      if (queryParams.minDuration && (!course.duration || course.duration < queryParams.minDuration)) {
        return false;
      }

      if (queryParams.maxDuration && (!course.duration || course.duration > queryParams.maxDuration)) {
        return false;
      }

      // 是否有先修课程
      if (queryParams.hasPrerequisites !== undefined) {
        const hasPrerequisites = course.prerequisites && course.prerequisites.length > 0;
        if (queryParams.hasPrerequisites !== hasPrerequisites) {
          return false;
        }
      }

      return true;
    });
  }

  /**
   * 验证分类ID是否存在
   * @param categoryIds 分类ID列表
   * @returns 验证结果
   */
  private async validateCategoryIds(categoryIds: string[]): Promise<OperationResult<void>> {
    try {
      const categoriesResult = await storageService.getItem<ICourseCategory[]>(STORAGE_KEYS.COURSE_CATEGORIES);
      if (!categoriesResult.success) {
        return {
          success: false,
          error: '无法获取课程分类信息'
        };
      }

      const categories = categoriesResult.data || [];
      const existingCategoryIds = categories.map(cat => cat.id);

      const invalidIds = categoryIds.filter(id => !existingCategoryIds.includes(id));
      if (invalidIds.length > 0) {
        return {
          success: false,
          error: `以下分类ID不存在: ${invalidIds.join(', ')}`
        };
      }

      return {
        success: true,
        data: undefined
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '验证分类ID失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 验证先修课程ID是否存在
   * @param prerequisiteIds 先修课程ID列表
   * @returns 验证结果
   */
  private async validatePrerequisiteIds(prerequisiteIds: string[]): Promise<OperationResult<void>> {
    try {
      const coursesResult = await this.getAllCourses();
      if (!coursesResult.success) {
        return coursesResult;
      }

      const courses = coursesResult.data;
      const existingCourseIds = courses.map(course => course.id);

      const invalidIds = prerequisiteIds.filter(id => !existingCourseIds.includes(id));
      if (invalidIds.length > 0) {
        return {
          success: false,
          error: `以下先修课程ID不存在: ${invalidIds.join(', ')}`
        };
      }

      return {
        success: true,
        data: undefined
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '验证先修课程ID失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 检查课程是否有关联的课表
   * @param courseId 课程ID
   * @returns 检查结果
   */
  private async checkCourseHasSchedule(courseId: string): Promise<OperationResult<boolean>> {
    try {
      // 检查课程模板
      const templatesResult = await storageService.getItem(STORAGE_KEYS.SCHEDULE_TEMPLATES);
      if (templatesResult.success && templatesResult.data) {
        const templates = Array.isArray(templatesResult.data) ? templatesResult.data : [];
        const hasTemplate = templates.some((template: any) => template.courseId === courseId);
        if (hasTemplate) {
          return {
            success: true,
            data: true
          };
        }
      }

      // 检查课程实例
      const instancesResult = await storageService.getItem(STORAGE_KEYS.SCHEDULE_INSTANCES);
      if (instancesResult.success && instancesResult.data) {
        const instances = Array.isArray(instancesResult.data) ? instancesResult.data : [];
        const hasInstance = instances.some((instance: any) => instance.courseId === courseId);
        if (hasInstance) {
          return {
            success: true,
            data: true
          };
        }
      }

      return {
        success: true,
        data: false
      };

    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : '检查课程课表关联失败';
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  /**
   * 获取课程的学生数量
   * @param courseId 课程ID
   * @returns 学生数量
   */
  private async getCourseStudentCount(courseId: string): Promise<number> {
    try {
      const templatesResult = await storageService.getItem(STORAGE_KEYS.SCHEDULE_TEMPLATES);
      if (!templatesResult.success || !templatesResult.data) {
        return 0;
      }

      const templates = Array.isArray(templatesResult.data) ? templatesResult.data : [];
      const uniqueStudentIds = new Set<string>();
      
      templates.forEach((template: any) => {
        if (template.courseId === courseId && template.studentId) {
          uniqueStudentIds.add(template.studentId);
        }
      });

      return uniqueStudentIds.size;

    } catch (error) {
      return 0;
    }
  }

  /**
   * 获取课程的课表数量
   * @param courseId 课程ID
   * @returns 课表数量
   */
  private async getCourseScheduleCount(courseId: string): Promise<number> {
    try {
      const templatesResult = await storageService.getItem(STORAGE_KEYS.SCHEDULE_TEMPLATES);
      if (!templatesResult.success || !templatesResult.data) {
        return 0;
      }

      const templates = Array.isArray(templatesResult.data) ? templatesResult.data : [];
      return templates.filter((template: any) => template.courseId === courseId).length;

    } catch (error) {
      return 0;
    }
  }

  /**
   * 获取课程的最近课程时间
   * @param courseId 课程ID
   * @returns 最近课程时间
   */
  private async getLastScheduleTime(courseId: string): Promise<string | undefined> {
    try {
      const instancesResult = await storageService.getItem(STORAGE_KEYS.SCHEDULE_INSTANCES);
      if (!instancesResult.success || !instancesResult.data) {
        return undefined;
      }

      const instances = Array.isArray(instancesResult.data) ? instancesResult.data : [];
      const courseInstances = instances.filter((instance: any) => instance.courseId === courseId);
      
      if (courseInstances.length === 0) {
        return undefined;
      }

      // 找到最近的课程时间
      const sortedInstances = courseInstances.sort((a: any, b: any) => {
        const dateA = new Date(`${a.date} ${a.startTime}`).getTime();
        const dateB = new Date(`${b.date} ${b.startTime}`).getTime();
        return dateB - dateA;
      });

      const lastInstance = sortedInstances[0];
      return `${lastInstance.date} ${lastInstance.startTime}`;

    } catch (error) {
      return undefined;
    }
  }

  /**
   * 生成随机颜色
   * @returns 颜色值
   */
  private generateRandomColor(): string {
    const colors = [
      '#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1',
      '#13c2c2', '#eb2f96', '#fa541c', '#a0d911', '#2f54eb'
    ];
    return colors[Math.floor(Math.random() * colors.length)];
  }

  /**
   * 生成课程ID
   * @returns 课程ID
   */
  private generateCourseId(): string {
    const timestamp = Date.now().toString(36);
    const randomStr = Math.random().toString(36).substr(2, 9);
    return `course_${timestamp}_${randomStr}`;
  }
}

/**
 * 默认课程服务实例
 */
export const courseService = new CourseService();